import time
import functools
import requests
from typing import Dict, Any, Tuple


def amap_call(api_key: str, timeout: int = 6, retries: int = 2, backoff: float = 0.4):
    """装饰器：为高德开放平台GET请求统一追加 key、超时与重试。

    被装饰函数需返回 (url, params) 元组。
    """

    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs) -> Dict[str, Any]:
            url, params = func(*args, **kwargs)
            params = {**(params or {}), 'key': api_key}
            last_err = None
            for i in range(retries + 1):
                try:
                    resp = requests.get(url, params=params, timeout=timeout)
                    resp.raise_for_status()
                    data = resp.json()
                    # v3接口 status 为 '1' 表示成功
                    if str(data.get('status')) == '1':
                        return data
                    raise RuntimeError(f"AMap error: {data}")
                except Exception as e:
                    last_err = e
                    if i < retries:
                        time.sleep(backoff * (2 ** i))
            raise last_err

        return wrapper

    return deco


def extract_hospitals_from_v3(place_resp: Dict[str, Any]):
    """从 v3 place/text 响应提取医院关键信息。"""
    pois = place_resp.get('pois') or []
    items = []
    for p in pois:
        name = p.get('name')
        location = p.get('location') or ''  # 'lng,lat'
        address = p.get('address')
        biz_ext = p.get('biz_ext') or {}
        rating = biz_ext.get('rating')
        # 距离（当传入 location 参数时，v3 会返回 distance，单位米的字符串）
        distance = p.get('distance')
        opentime = p.get('opentime') or biz_ext.get('open_time') or p.get('business')
        tel = p.get('tel')
        typecode = p.get('typecode')
        items.append({
            'name': name,
            'location': location,
            'address': address,
            'rating': rating,
            'distance': distance,
            'open_time': opentime,
            'tel': tel,
            'typecode': typecode,
        })
    return items


